package com.house.rent.ui.activity;


import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.KeyEvent;

import androidx.core.content.ContextCompat;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;

import com.base.lib.mvp.present.BasePresenter;
import com.base.lib.util.ScreenManager;
import com.base.lib.util.StatusBarUtil;
import com.base.lib.widget.BottomBarLayout;
import com.house.rent.App;
import com.house.rent.R;
import com.house.rent.ui.dialog.PublishDialog;
import com.house.rent.ui.fragment.MainFragment;
import com.house.rent.ui.fragment.MineFragment;

import butterknife.BindView;


/**
 * @author neo.duan
 * @date 2019/09/09
 * @desc 首页
 */
public class MainActivity extends BaseActivity {
    private static final String TAB_INDEX = "tab_index";
    private static final long INTERVAL = 2000;
    private static final int INDEX_MAIN = 0;
    private static final int INDEX_MINE = 3;
    @BindView(R.id.nav_main_bottom)
    BottomBarLayout mBottomBarLayout;
    /**
     * 当前被选中
     */
    private int mCurrentIndex = INDEX_MAIN;
    /**
     * Fragment集合
     */
    private Fragment[] mFragments = new Fragment[4];
    /**
     * 再按一次退出程序
     */
    private long exitTime = 0;

    public static void start(Context context) {
        Intent starter = new Intent(context, MainActivity.class);
        context.startActivity(starter);
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putInt(TAB_INDEX, mCurrentIndex);
    }

    @Override
    protected int getLayoutResId() {
        return R.layout.activity_main;
    }

    @Override
    protected void initTop() {
        enableTop(false);
    }

    @Override
    protected void initView(Bundle savedInstanceState) {
        initFragment(savedInstanceState);
    }

    @Override
    protected void initListeners() {
        mBottomBarLayout.setOnBottomItemSelectedListener((item, position) -> {
            switch (position) {
                case 0:
                    selectFragment(INDEX_MAIN);
                    break;
                case 1:
                    if (!App.getInstance().getUserEntity().isAudit()) {
                        showMessage("身份信息未审核通过,无法发布");
                        return;
                    }

                    PublishDialog dialog = new PublishDialog(mContext);
                    dialog.setOnPublishListener((dialog1, position1) -> {
                        dialog1.dismiss();
                        //类型 0-出售 1-求购 2-求租 3-出租
                        switch (position1) {
                            case 0: //发布出售
                                PublishActivity.start(mContext, 0);
                                break;
                            case 1://发布出租
                                PublishActivity.start(mContext, 3);
                                break;
                            case 2://发布求购
                                PublishActivity.start(mContext, 1);
                                break;
                            case 3://发布求租
                                PublishActivity.start(mContext, 2);
                                break;
                            default:
                                break;
                        }

                    });
                    dialog.show();
                    break;
                case 2:
                    selectFragment(INDEX_MINE);
                    break;
                default:
                    selectFragment(INDEX_MAIN);
                    break;
            }
            setTitle(mBottomBarLayout.getTextArr()[position]);
        });
    }

    @Override
    protected BasePresenter initPresenter() {
        return null;
    }

    @Override
    protected void initData() {

    }

    /**
     * 初始化Fragment
     */
    private void initFragment(Bundle savedInstanceState) {
        //无缓存情况
        if (savedInstanceState == null) {
            MainFragment houseFragment = MainFragment.newInstance();
            mFragments[INDEX_MAIN] = houseFragment;

            MineFragment mPersonalCenterFragment = MineFragment.newInstance();
            mFragments[INDEX_MINE] = mPersonalCenterFragment;

            //Fragment事务初始化
            getSupportFragmentManager().beginTransaction()
                    .add(R.id.fl_main_container, mFragments[INDEX_MAIN], MainFragment.class.getName())
                    .add(R.id.fl_main_container, mFragments[INDEX_MINE], MineFragment.class.getName())
                    .hide(mFragments[INDEX_MINE])
                    .show(mFragments[INDEX_MAIN])

                    .addToBackStack(null)
                    .commitAllowingStateLoss();
        } else {
            // 有缓存情况，取出来重新引用
            FragmentManager fragmentManager = getSupportFragmentManager();
            mFragments[INDEX_MAIN] = fragmentManager.findFragmentByTag(MainFragment.class.getName());
            mFragments[INDEX_MINE] = fragmentManager.findFragmentByTag(MineFragment.class.getName());

            mCurrentIndex = savedInstanceState.getInt(TAB_INDEX, INDEX_MAIN);
        }
        selectFragment(mCurrentIndex);
    }

    /**
     * Fragment选择
     */
    private void selectFragment(int selectedIndex) {
        if (selectedIndex != mCurrentIndex) {
            getSupportFragmentManager().beginTransaction()
                    .hide(mFragments[mCurrentIndex])
                    .show(mFragments[selectedIndex])

                    .addToBackStack(null)
                    .commitAllowingStateLoss();
            mCurrentIndex = selectedIndex;

            //处理状态栏
            if (mFragments[selectedIndex] instanceof MineFragment) {
                StatusBarUtil.setColor(this, ContextCompat.getColor(getApplicationContext(), R.color.black), 0);
            } else {
                StatusBarUtil.setColor(this, ContextCompat.getColor(getApplicationContext(), R.color.colorAccent), 0);
            }
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN) {
            if ((System.currentTimeMillis() - exitTime) > INTERVAL) {
                exitTime = System.currentTimeMillis();
                showMessage("再按一次退出程序");
            } else {
                ScreenManager.getInstance().popAllActivity();
            }

            return true;
        }

        return super.onKeyDown(keyCode, event);
    }
}
